package servlet;

import dao.ProductDAO;
import pojo.Product;
import utils.ApiResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/product")
public class ProductServlet extends BaseServlet {

    // 添加商品
    public void addProduct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String productName = req.getParameter("productName");
        String description = req.getParameter("description");
        String imageUrl = req.getParameter("imageUrl");

        Product product = new Product();
        product.setProductName(productName);
        product.setDescription(description);
        product.setImageUrl(imageUrl);

        try {
            ProductDAO.addProduct(product);
            sendJsonResponse(resp, new ApiResult(200, "添加商品成功", null));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "添加商品失败", e.getMessage()));
        }
    }

    // 更新商品信息
    public void updateProduct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int productId = Integer.parseInt(req.getParameter("productId"));
        String productName = req.getParameter("productName");
        String description = req.getParameter("description");
        String imageUrl = req.getParameter("imageUrl");

        Product product = new Product();
        product.setProductId(productId);
        product.setProductName(productName);
        product.setDescription(description);
        product.setImageUrl(imageUrl);

        try {
            ProductDAO.updateProduct(product);
            sendJsonResponse(resp, new ApiResult(200, "更新商品信息成功", null));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "更新商品信息失败", e.getMessage()));
        }
    }

    // 删除商品
    public void deleteProduct(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int productId = Integer.parseInt(req.getParameter("productId"));

        try {
            ProductDAO.deleteProduct(productId);
            sendJsonResponse(resp, new ApiResult(200, "删除商品成功", null));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "删除商品失败", e.getMessage()));
        }
    }

    // 获取所有商品
    public void getAllProducts(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Product> products = ProductDAO.getAllProducts();
            sendJsonResponse(resp, new ApiResult(200, "获取所有商品成功", products));
        } catch (SQLException e) {
            sendJsonResponse(resp, new ApiResult(500, "获取所有商品失败", e.getMessage()));
        }
    }

}
